<template>
  <div class="app-container">
    <div class="page-header">
      <el-form :inline="true" :model="search">
        <el-form-item label="统计类型">
          <el-select
            v-model="search.type"
            placeholder="请选择 统计类型"
            @change="searchTypeChange"
          >
            <el-option label="销售数据" value="0" />
            <el-option label="近7天销售" value="1" />
            <el-option label="近30天销售" value="2" />
          </el-select>
        </el-form-item>
        <el-form-item label="店铺">
          <el-select
            v-model="search.mallId"
            placeholder="请选择 店铺"
            clearable
            @change="selectMall"
          >
            <el-option
              v-for="item in mallList"
              :key="item.mallId"
              :label="item.mallName"
              :value="item.mallId + ''"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <el-progress
        v-if="!!mallId"
        :width="50"
        type="circle"
        :status="saleDataStatus.percent >= 100 ? 'success' : ''"
        :percentage="saleDataStatus.percent"
        class="data-progress"
      />
    </div>
    <div class="box-card">
      <template v-for="(data, index) in saleList" :key="index">
        <div v-show="data.display" class="data-block">
          <span>{{ data.label }}</span>
          <span :style="{ color: data.color }">{{ data.value }}</span>
        </div>
      </template>
    </div>
    <div class="content" v-loading="dataLoading">
      <el-table :data="tableData" border style="width: 100%; height: 100%">
        <el-table-column type="index" label="序号" width="100" />
        <el-table-column prop="productName" label="商品名称" width="220">
          <template v-slot="{ row }">
            <el-tooltip
              effect="dark"
              :content="row.productName"
              placement="top-start"
            >
              <span class="hidden-text">{{ row.productName }}</span>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column prop="productId" label="SPU" width="180" />
        <el-table-column prop="productSkcId" label="SKC" width="180" />
        <el-table-column prop="productSkuId" label="SKU ID" width="180" />
        <el-table-column prop="className" label="SKU属性" width="180" />
        <el-table-column prop="skuExtCode" label="SKU货号" width="180" />
        <el-table-column label="加入站点时长">
          <template v-slot="{ row }">
            {{ row.onSalesDurationOffline || '-' }} 天
          </template>
        </el-table-column>
        <el-table-column width="120" label="开款核价状态">
          <template v-slot="{ row }">
            {{ row.isVerifyPrice ? '核价通过' : '核价未通过 / 无法备货' }}
          </template>
        </el-table-column>
        <template v-if="search.type === '0'">
          <el-table-column
            fixed="right"
            prop="todaySaleVolume"
            label="今日销量"
            width="150"
            sortable
          />
        </template>
        <template v-else-if="search.type === '1'">
          <el-table-column
            fixed="right"
            prop="lastSevenDaysSaleVolume"
            label="近7日销量"
            width="150"
            sortable
          />
        </template>
        <template v-else-if="search.type === '2'">
          <el-table-column
            fixed="right"
            prop="lastThirtyDaysSaleVolume"
            label="近30日销量"
            width="150"
            sortable
          />
        </template>
        <el-table-column
          fixed="right"
          width="160"
          label="申报价格(CNY)"
          prop="supplierPriceFormat"
          sortable
        />
        <el-table-column
          fixed="right"
          width="160"
          label="仓内可用库存"
          prop="warehouseInventoryNum"
          sortable
        />
        <el-table-column
          fixed="right"
          width="160"
          label="库存货值(CNY)"
          prop="productTotalPrice"
          sortable
        />
      </el-table>
    </div>
    <div class="pagination-bar">
      <el-pagination
        v-model:current-page="pageId"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="totalNum"
        background
        @current-change="getData"
        @size-change="getData"
      />
    </div>
  </div>
</template>

<script setup>
import { computed, reactive, ref } from 'vue'
import { onBeforeRouteLeave } from 'vue-router'
import { useUserStore } from '@/store/user'
import { ElMessage as message } from 'element-plus'
import { getSaleData } from '@/api/user'

const userStore = useUserStore()
const sysUser = computed(() => userStore.sysUser)
const mallList = computed(() => {
  if (userStore.userInfo?.companyList && userStore.userInfo?.companyList[0]) {
    return userStore.userInfo.companyList[0].malInfoList
  } else {
    return []
  }
})
const search = ref({
  type: '0',
  mallId: ''
})
const tableData = ref([])
const dataLoading = ref(false)
const mallId = ref('')
const saleList = ref([])
const pageSize = ref(10)
const pageId = ref(1)
const totalNum = ref(0)
const saleDataStatus = reactive({
  loading: false,
  percent: 0,
  isError: false,
  timer: null
})

const searchTypeChange = (val) => {
  const labelsToday = ['今日销量', '今日销售额']
  const labelsSeven = ['近7日销量', '近7日销售额']
  const labelsThirty = ['近30日销量', '近30日销售额']
  const allLabels = [...labelsToday, ...labelsSeven, ...labelsThirty]
  saleList.value = saleList.value.map((item) => {
    if (allLabels.includes(item.label)) {
      item.display = false
      if (
        (val === '0' && labelsToday.includes(item.label)) ||
        (val === '1' && labelsSeven.includes(item.label)) ||
        (val === '2' && labelsThirty.includes(item.label))
      ) {
        item.display = true
      }
    } else {
      item.display = true
    }
    return item
  })
  console.log(saleList.value)
}
// 选择了店铺
const selectMall = (val) => {
  cancelLoop()
  mallId.value = val
  getData()
}
const getData = () => {
  const val = mallId.value
  tableData.value = []
  saleList.value = [
    {
      label: '今日销量', // todayTotal
      value: 0,
      color: '#2266ff',
      display: search.value.type === '0'
    },
    {
      label: '今日销售额', // todayMoney
      value: 0,
      color: '#f8b426',
      display: search.value.type === '0'
    },
    {
      label: '近7日销量', // todayTotal
      value: 0,
      color: '#2266ff',
      display: search.value.type === '1'
    },
    {
      label: '近7日销售额', // todayMoney
      value: 0,
      color: '#f8b426',
      display: search.value.type === '1'
    },
    {
      label: '近30日销量', // todayTotal
      value: 0,
      color: '#2266ff',
      display: search.value.type === '2'
    },
    {
      label: '近30日销售额', // todayMoney
      value: 0,
      color: '#f8b426',
      display: search.value.type === '2'
    },
    {
      label: '库存总量', // inventoryTotal
      value: 0,
      color: '#21aa99',
      display: true
    },
    {
      label: '库存总额', // inventoryMoeny
      value: 0,
      color: '#ff4466',
      display: true
    },
    {
      label: '已收货总量', // deliveryTotal
      value: 0,
      color: '#11a265',
      display: true
    },
    {
      label: '已收货总货值', // deliveryMoeny
      value: 0,
      color: '#000000',
      display: true
    }
  ]
  if (!val) return
  if (sysUser.value.user_level === 0) {
    return message.error('请激活账号，才可使用此功能')
  }
  if (
    sysUser.value.user_level === 1 &&
    sysUser.value.boundled_mallShops.length === 0
  ) {
    return message.error('请先绑定店铺')
  }
  const bid = sysUser.value.bindMallIds || []
  if (!bid.includes(val)) return message.error('请选择绑定该账号的店铺！')
  saleDataStatus.loading = true
  loopGetData(val)
}
const sleep = (time) => {
  return new Promise((resolve) => {
    saleDataStatus.timer = setTimeout(() => {
      resolve()
    }, time)
  })
}
const loopGetData = async (mid) => {
  try {
    const { result, totalShopInfo, total, loadPercent } = await getRealData(mid)
    saleDataStatus.percent = Number((loadPercent * 100).toFixed(0))
    if (saleDataStatus.loading) {
      intiData({ result, totalShopInfo, total, loadPercent })
      if (loadPercent === 1) {
        saleDataStatus.loading = false
      } else {
        await sleep(3000)
        await loopGetData(mid)
      }
    }
  } catch (e) {
    cancelLoop()
  }
}
const cancelLoop = () => {
  clearTimeout(saleDataStatus.timer)
  saleDataStatus.loading = false
  saleDataStatus.percent = 0
  saleDataStatus.isError = false
  saleDataStatus.timer = null
}
const intiData = ({ result, totalShopInfo, total }) => {
  try {
    tableData.value = []
    dataLoading.value = true
    totalNum.value = total
    result.forEach((order) => {
      if (Array.isArray(order.skuQuantityDetailList)) {
        order.skuQuantityDetailList.forEach((o) => {
          o.productName = order.productName
          o.productId = order.productId
          o.productSkcId = order.productSkcId
          o.supplierPriceFormat = o.supplierPrice / 100 || 0
          o.warehouseInventoryNum = Number(
            o.inventoryNumInfo.warehouseInventoryNum
          )
          o.productTotalPrice = Number(
            (
              ((o.supplierPrice || 0) / 100) *
              o.inventoryNumInfo.warehouseInventoryNum
            ).toFixed(2)
          )
        })
        tableData.value.push(...order.skuQuantityDetailList)
      }
    })
    calcSaleListData(totalShopInfo)
  } finally {
    dataLoading.value = false
  }
}
const getRealData = async (mallId) => {
  const {
    shopInfoDetailList: result,
    totalShopInfo,
    total,
    loadPercent
  } = await getSaleData({
    mallId,
    pageId: pageId.value,
    pageSize: pageSize.value
  })

  return {
    result,
    totalShopInfo,
    total,
    loadPercent
  }
}
// 计算销售数据
const calcSaleListData = async (total) => {
  saleList.value = [
    {
      label: '今日销量', // todayTotal
      value: total.todaySaleVolume || 0,
      color: '#2266ff',
      display: search.value.type === '0'
    },
    {
      label: '今日销售额', // todayMoney
      value: (Number(total.todaySalePrice || 0) / 100).toFixed(0),
      color: '#f8b426',
      display: search.value.type === '0'
    },
    {
      label: '近7日销量',
      value: total.lastSevenDaysSaleVolume || 0,
      color: '#2266ff',
      display: search.value.type === '1'
    },
    {
      label: '近7日销售额',
      value: (Number(total.lastSevenDaysSalePrice || 0) / 100).toFixed(0),
      color: '#f8b426',
      display: search.value.type === '1'
    },
    {
      label: '近30日销量',
      value: total.lastThirtyDaysSaleVolume || 0,
      color: '#2266ff',
      display: search.value.type === '2'
    },
    {
      label: '近30日销售额',
      value: (Number(total.lastThirtyDaysSalePrice || 0) / 100).toFixed(0),
      color: '#f8b426',
      display: search.value.type === '2'
    },
    {
      label: '库存总量', // inventoryTotal
      value: total.warehouseInventoryNum || 0,
      color: '#21aa99',
      display: true
    },
    {
      label: '库存总额', // inventoryMoeny
      value: (Number(total.warehouseInventorytotalPrice || 0) / 100).toFixed(0),
      color: '#ff4466',
      display: true
    },
    {
      label: '已收货总量', // deliveryTotal
      value: total.totalSaleVolume || 0,
      color: '#11a265',
      display: true
    },
    {
      label: '已收货总货值', // deliveryMoeny
      value: (Number(total.totalSalePrice || 0) / 100).toFixed(0),
      color: '#000000',
      display: true
    }
  ]
}

onBeforeRouteLeave(() => {
  console.log('unmmmmm')
  cancelLoop()
})
</script>

<style lang="scss" scoped>
.data-progress {
  :deep(.el-progress__text) {
    font-size: 15px !important;
  }
}
.app-container {
  margin: 20px;
  padding: 20px;
  background-color: #fff;
  height: calc(100vh - 130px);
  overflow: hidden;
  display: flex;
  flex-direction: column;
  .page-header {
    display: flex;
    align-items: center;
    justify-content: center;
    .el-form {
      flex: 1;
    }
    .el-progress {
      margin-bottom: 22px;
    }
  }
  .loading-wrap {
    height: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
    flex-direction: column;
    span {
      padding-top: 15px;
      font-weight: bold;
    }
    .el-button {
      margin-top: 10px;
    }
  }
  .box-card {
    margin-bottom: 15px;
    display: flex;
    padding: 5px 0;
    .data-block {
      width: 16.5%;
      display: flex;
      flex-direction: column;
      margin-right: 15px;
      background: #fff;
      padding: 15px;
      border: solid 1px #e3e3e3;
      border-radius: 4px;
      &:last-child {
        margin-right: 0;
      }
      span:nth-child(1) {
        margin-bottom: 30px;
        font-size: 16px;
        color: #999;
      }
      span:nth-child(2) {
        font-weight: 600;
        font-size: 28px;
      }
    }
  }
  .content {
    flex: 1;
    height: 100%;
    overflow: hidden;
  }
  .pagination-bar {
    padding-top: 15px;
    display: flex;
    justify-content: center;
  }
}
.hidden-text {
  display: inline-block;
  width: 180px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
</style>
